package com.byl.common.interceptor;

import com.byl.common.modules.service.TokenService;
import com.byl.sdk.bean.Response;
import com.byl.sdk.gson.GsonUtils;
import com.byl.sdk.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2019/12/5.
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         String token=request.getHeader("X-Token");
        //如果没有token 拒绝访问
        if(StringUtil.isBlank(token)){
            fail(response,"no access token",1);
            return false;
        }
        //验证token有效性
        int v=tokenService.verifyToken(token);
        //token 无效  拒绝访问
        if(v==2){
            fail(response,"expire token",2);
            return false;
        }else if(v==3){
            fail(response,"invalid token",3);
            return false;
        }

        return true;
    }

    private void fail(HttpServletResponse response, String msg,int code) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            writer = response.getWriter();
            writer.print(GsonUtils.beanToJson(new Response(code, msg)));
        } catch (IOException e) {

        } finally {
            if (writer != null)
                writer.close();
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("########TokenInterceptor>>>>>>>>postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("########TokenInterceptor>>>>>>>>afterCompletion");
    }

}
